package com.sec.etech.employeesync.config;

import com.sec.etech.employeesync.util.ConfigHandler;
import lombok.extern.slf4j.Slf4j;
import org.openbpm.base.api.exception.BusinessException;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ConfigManager {

    private final Map<String, ConfigHandler> configHandlers;

    private final Map<String, Map<String, Long>> configCache = new ConcurrentHashMap<>();

    public ConfigManager(Map<String, ConfigHandler> configHandlers) {
        this.configHandlers = configHandlers;
    }

    public void initAllConfig() {
        Map<String, Map<String, Long>> newConfigCache = configHandlers.entrySet().parallelStream()
                .collect(Collectors.toConcurrentMap(
                        entry -> entry.getKey().replace("Handler", ""),
                        entry -> {
                            ConfigHandler handler = entry.getValue();
                            return handler.getAllConfigs().stream()
                                    .collect(Collectors.toConcurrentMap(
                                            config -> createCacheKey(config.getParams()),
                                            ConfigHandler.ConfigEntry::getId,
                                            (a, b) -> a
                                    ));
                        }
                ));

        configCache.clear();
        configCache.putAll(newConfigCache);
    }

    public Long getConfigId(String configType, String... params) {
        Map<String, Long> typeCache = configCache.get(configType);
        if (typeCache == null) {
            return null;
        }

        String key = createCacheKey(params);
        return typeCache.get(key);
    }

    private String createCacheKey(String... params) {
        return String.join(":", params);
    }

    public void createConfig(String configType, String... params) {
        // 首先尝试从缓存中获取配置ID
        Long configId = getConfigId(configType, params);
        if (configId == null) {
            // 如果缓存中不存在，则进行数据库查询和插入
            createConfigSync(configType, params);
        }
    }

    private void createConfigSync(String configType, String... params) {
        ConfigHandler configHandler = configHandlers.get(configType + "Handler");
        if (configHandler == null) {
            throw new BusinessException("找不到处理器");
        }

        synchronized (this) {
            // 再次查询以避免并发插入
            Long existingId = getConfigId(configType, params);
            if (existingId == null) {
                // 更新缓存
                Map<String, Long> typeCache = configCache.computeIfAbsent(configType, k -> new ConcurrentHashMap<>());
                typeCache.computeIfAbsent(createCacheKey(params), k -> configHandler.createConfig(params));
            }
        }
    }


}
